<script setup lang="ts">
interface IProps {
  expectedTime: string;
}

interface IState {
  show: boolean;
  expectedTime: string;
  columns: Array<{ values: string[]; defaultIndex?: number }>;
  timeRanges?: { [key: string]: string[] };
}

type EmitEvents = {
  (event: 'change', payload: string): void;
};

const props = defineProps<IProps>();
const state = reactive<IState>({ show: false, expectedTime: '', columns: [] });
const emits = defineEmits<EmitEvents>();

onMounted(() => {
  if (props.expectedTime.includes('~')) {
    const expectedTime = props.expectedTime.split('~');
    expectedTime[0] = determineDay(expectedTime[0]) === '今天' || determineDay(expectedTime[0]) === '明天' ? determineDay(expectedTime[0]) + expectedTime[0].substring(11, expectedTime[0].length) : expectedTime[0];
    expectedTime[1] = determineDay(expectedTime[1]) === '今天' || determineDay(expectedTime[1]) === '明天' ? determineDay(expectedTime[1]) + expectedTime[1].substring(11, expectedTime[1].length) : expectedTime[1];
    state.expectedTime = expectedTime[0] + ' ~ ' + expectedTime[1];
    state.timeRanges = generateTimeRanges(expectedTime[1].substring(11, expectedTime[1].length));
  } else {
    state.expectedTime = determineDay(props.expectedTime) === '今天' || determineDay(props.expectedTime) === '明天' ? determineDay(props.expectedTime) + props.expectedTime.substring(10, props.expectedTime.length) : props.expectedTime;
    state.timeRanges = generateTimeRanges(props.expectedTime.substring(11, props.expectedTime.length));
  }
  state.columns = [{ values: Object.keys(state.timeRanges) }, { values: state.timeRanges[Object.keys(state.timeRanges)[0]], defaultIndex: 2 }];
});

// 选择弃change事件处理
const handlePickerChange = (event: any) => {
  const { picker, value } = event.detail;
  picker.setColumnValues(1, state.timeRanges![value[0]]);
};

// 选择器选中事件
const handlePickerConfirm = (event: any) => {
  state.expectedTime = event.detail.value[0] + ' ' + event.detail.value[1];
  emits('change', event.detail.value[0] + ' ' + event.detail.value[1]);
  state.show = false;
};

// 判断日期是今天、明天还是其他日期
function determineDay(dateStr: string): string {
  const inputDate = new Date(dateStr);
  if (isNaN(inputDate.getTime())) {
    return dateStr;
  }

  const now = new Date();
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  const tomorrow = new Date(today);
  tomorrow.setDate(today.getDate() + 1);

  const inputDay = new Date(inputDate.getFullYear(), inputDate.getMonth(), inputDate.getDate());

  if (inputDay.getTime() === today.getTime()) {
    return '今天';
  } else if (inputDay.getTime() === tomorrow.getTime()) {
    return '明天';
  } else {
    return dateStr;
  }
}

// 生成未来五天的时间范围对象
function generateTimeRanges(startTime: string): Record<string, string[]> {
  const result: Record<string, string[]> = {};
  const now = new Date();

  // 解析传入时间
  const [startHour, startMinute] = startTime.split(':').map(Number);
  const todayStartTime = new Date(now.setHours(startHour, startMinute, 0, 0));
  const startOfDay = new Date(now.setHours(7, 0, 0, 0)); // 每天的起始时间
  const endOfDay = new Date(now.setHours(17, 0, 0, 0)); // 每天的结束时间

  // 确定今天的起始时间列表
  const todaySlots: string[] = [];
  if (todayStartTime < startOfDay) {
    todaySlots.push(startTime); // 如果传入时间小于 7:00，先插入传入时间
    todayStartTime.setHours(7, 0, 0, 0); // 起始时间从 7:00 开始计算
  } else {
    const extraMinutes = todayStartTime.getMinutes() % 15;
    if (extraMinutes > 0) {
      // 调整到下一个有效的 15 分钟分隔点
      todayStartTime.setMinutes(todayStartTime.getMinutes() + (15 - extraMinutes));
    }
    todaySlots.push(startTime);
  }

  // 生成未来五天的时间范围
  for (let i = 0; i < 5; i++) {
    const currentDate = new Date(now);
    currentDate.setDate(now.getDate() + i);
    const year = currentDate.getFullYear();
    const month = String(currentDate.getMonth() + 1).padStart(2, '0');
    const day = String(currentDate.getDate()).padStart(2, '0');
    const dateKey = `${year}-${month}-${day}`;
    const timeSlots: string[] = [];

    // 今天的时间段逻辑
    if (i === 0) {
      let currentTime = new Date(todayStartTime);
      while (currentTime <= endOfDay) {
        const hours = String(currentTime.getHours()).padStart(2, '0');
        const minutes = String(currentTime.getMinutes()).padStart(2, '0');
        timeSlots.push(`${hours}:${minutes}`);
        currentTime.setMinutes(currentTime.getMinutes() + 15);
      }
      result[dateKey] = todaySlots.concat(timeSlots); // 合并今天的插入时间和计算时间段
    } else {
      // 非今天逻辑，从 7:00 到 17:00
      let currentTime = new Date(startOfDay);
      while (currentTime <= endOfDay) {
        const hours = String(currentTime.getHours()).padStart(2, '0');
        const minutes = String(currentTime.getMinutes()).padStart(2, '0');
        timeSlots.push(`${hours}:${minutes}`);
        currentTime.setMinutes(currentTime.getMinutes() + 15);
      }
      result[dateKey] = timeSlots;
    }
  }

  return result;
}
</script>

<template>
  <view class="flex justify-between mt-12px text-red" @click="state.show = true">
    <text>预计到达时间：</text>
    <view class="flex items-center">
      <text>{{ state.expectedTime }}</text>
      <i class="i-icon-park-outline:right ml-4px"></i>
    </view>
  </view>
  <van-popup position="bottom" round :show="state.show" @close="state.show = false">
    <view class="bg-white w-full">
      <van-picker show-toolbar value-key="text" :columns="state.columns" title="请选择预计送达时间" @change="handlePickerChange" @cancel="state.show = false" @confirm="handlePickerConfirm" />
    </view>
  </van-popup>
</template>
